package com.zsc.wxm.ysh.anjo.security;

import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.service.base.utils.SpringContext;
import com.zsc.wxm.ysh.anjo.utils.JwtUtil;
import com.zsc.wxm.ysh.anjo.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述： 退出处理器
 *
 * @author playmaker
 * @since 2021/2/6 15:33
 */
public class SecurityLogoutHandler implements LogoutHandler {

    private RedisTemplate<String, String> redisTemplate = SpringContext.getBean(RedisTemplate.class);

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            JwtUtil.removeToken(token);
            String phone = JwtUtil.getUserPhoneByToken(token);
            if (StringUtils.isNotBlank(phone)) {
                redisTemplate.delete(phone);
            }
        }
        ResponseUtil.response(httpServletResponse, Result.ok("退出成功"));
    }
}
